<?php

/**
 * 抽奖小程序相关接口
 * 作者：刘单风
 * 最后修改时间：2018-11-14
 * 版权：医库PHP小组
 */
namespace app\api\controller;
use app\api\controller\apiinterface\ILuckprize;
use app\model\Address;
use app\model\Luckprizes;
use MoCommon\DataState\PrizeCodes;
use MoCommon\Services\UploadFiles;
use MoCommon\Support\Codes;
use MoCommon\DataState\AddressCodes;
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Config;
use think\facade\Env;

class Luckprize extends Apibase implements ILuckprize
{
    private static $luckprizeModel;
    public function __construct()
    {
        self::$luckprizeModel=new Luckprizes();
    }

    /**
     * 小程序首页
     */
    function index()
    {
        $userid = parent::getUid(1);
        //精品奖品
        $indexprize = self::$luckprizeModel->indexprize($userid);
        //获取十条已开奖的数据
        $openprize = self::$luckprizeModel->openprize(1, $userid);
        $status = $userid ? Codes::ACTION_SUC : Codes::NO_SIGNIN;
        $msg = Codes::get($status);
        $data = array(
            'index_prize' => $indexprize,
            'open_prize' => $openprize['openprize'],
            'open_count'=>$openprize['opencount']
        );
        return parent::respond($data, $status, $msg);
    }

    /**
     * 已开奖数据列表
     */
    function openprize()
    {
        $userid = parent::getUid();
        $cpage = input('cpage', 2);
        $openprize = self::$luckprizeModel->openprize($cpage, $userid);
        return parent::respond($openprize['openprize']);
    }

    /**
     * 奖品详情
     */
    function prizedetail()
    {
        $userid = parent::getUid(1);
        $prizeid = input('prizeid', 0);
        $inviteid = input('inviteid', 0);
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            $data = [];
        } else {
            $data = self::$luckprizeModel->prizedetail($userid, $prizeid, $inviteid);
            $status = $userid ? Codes::ACTION_SUC : Codes::NO_SIGNIN;
            $msg = Codes::get($status);
        }
        return parent::respond($data, $status, $msg);
    }

    /**
     * 幸运指数邀请人列表
     */
    function luckstarlist()
    {
        $userid = parent::getUid();
        $prizeid = input('prizeid', 0);
        $cpage = input('cpage', 1);
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            $data = [];
        } else {
            $data = self::$luckprizeModel->luckstars($userid,$prizeid, $cpage);
            $status = Codes::ACTION_SUC;
            $msg = Codes::get($status);
        }
        return parent::respond($data, $status, $msg);
    }

    /**
     * 中奖者列表数据
     */
    function winnerlist()
    {
        $userid = parent::getUid();
        $prizeid = input('prizeid', 0);
        $cpage = input('cpage', 1);
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            $data = [];
        } else {
            $data = self::$luckprizeModel->prizewinners($prizeid, $cpage);
            $status = Codes::ACTION_SUC;
            $msg = Codes::get($status);
        }
        return parent::respond($data, $status, $msg);
    }


    /**
     * 参与抽奖
     */
    function joinprize()
    {
        $userid = parent::getUid();
        $prizeid = input('prizeid', 0);
        $inviteid = input('inviteid', 0);
        $formid = input('formid', "");
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
        } else {
            //用户参与抽奖
            $result = self::$luckprizeModel->userjoin($userid, $prizeid, $inviteid, $formid);
            if ($result['result'] == 0) {
                $status = Codes::ACTION_SUC;
                $msg = Codes::get($status);
            } else if ($result['result'] == 1) {
                //用户参与过这个抽奖了
                $status = PrizeCodes::DATA_EXIST;
                $msg = PrizeCodes::get($status);
            } else if ($result['result'] == 2) {
                //这个抽奖结束了
                $status = PrizeCodes::DATA_FINISH;
                $msg = PrizeCodes::get($status);
            } else if ($result['result'] == 3) {
                //组队已经完成了,无法再加入这个战队了
                $status = PrizeCodes::DATA_FULL;
                $msg = PrizeCodes::get($status);
            }
        }
        return parent::respond([], $status, $msg);
    }

    /**
     * 获取参与用户
     */
    function joinusers()
    {
        $prizeid = input('prizeid', 0);
        $cpage = input('cpage', 1);
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            $data = [];
        } else {
            $data = self::$luckprizeModel->joinusers($prizeid, $cpage);
            $status = Codes::ACTION_SUC;
            $msg = Codes::get($status);
        }
        return parent::respond($data, $status, $msg);
    }

    /**
     * 发起人查看中奖者收货地址
     */
    function winneraddress()
    {
        $userid = parent::getUid();
        $prizeid = input('prizeid', 0);
        $cpage = input('cpage', 1);
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            $data = [];
        } else {
            $resultarr = self::$luckprizeModel->winneraddr($userid, $prizeid,$cpage);
            if ($resultarr['result'] == 0) {
                $status = Codes::ACTION_SUC;
                $msg = Codes::get($status);
                $data = $resultarr['addrs'];
            } else if ($resultarr['result'] == 1) {
                //当前用户不是这个抽奖的发起人,不能查看中奖者收货地址
                $status = PrizeCodes::DATA_NOT_OWN;
                $msg = PrizeCodes::get($status);
                $data = $resultarr['addrs'];
            } else {
                //还未开奖
                $status = PrizeCodes::DATA_NOT_OPEN;
                $msg = PrizeCodes::get($status);
                $data = $resultarr['addrs'];
            }
        }
        return parent::respond($data, $status, $msg);
    }

    /**
     * 中奖者领取奖品
     */
    function receiveprize()
    {
        $userid = parent::getUid();
        $prizeid = input('prizeid', 0);
        $addrid = input('addrid', 0);
        $consignee = input('consignee');
        $link_phone = input('link_phone');
        $link_area = input('link_area');
        $link_address = input('link_address');
        $is_default = input('is_default', 0);
        if (empty($addrid) && (empty($consignee) || empty($link_phone) || empty($link_area) || empty($link_address))) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            return parent::respond([], $status, $msg);
        }
        if (empty($addrid)) {
            //新增地址
            $addressModel = new Address();
            $data = [
                'consignee' => $consignee,
                'link_phone' => $link_phone,
                'link_area' => $link_area,
                'link_address' => $link_address,
                'is_default' => $is_default,
                'user_id' => $userid
            ];
            $isdata = $addressModel->isExist($data);
            if (empty($isdata)) {
                if ($is_default == 1) {
                    //说明当前的为默认地址,将其他地址取消默认
                    $addressModel->updateOne(['is_default' => 0], ['user_id' => $userid]);
                }
                $addrid = $addressModel->addOne($data);
            } else {
                //收货地址已存在
                $status = AddressCodes::DATA_EXIST;
                $msg = AddressCodes::get($status);
                return parent::respond([], $status, $msg);
            }
        }
        $resultarr = self::$luckprizeModel->receiveprize($userid, $prizeid, $addrid);
        if ($resultarr == 0) {
            $status = Codes::ACTION_SUC;
            $msg = Codes::get($status);
        } else if ($resultarr == 1) {
            //没中奖,不能领取
            $status = PrizeCodes::DATA_NO_PRIZE;
            $msg = PrizeCodes::get($status);
        } else {
            //已经领过了
            $status = PrizeCodes::DATA_ACCEPT_PRIZE;
            $msg = PrizeCodes::get($status);
        }
        return parent::respond([], $status, $msg);
    }

    /**
     * 创建抽奖
     */
    function createprize()
    {
        $userid = parent::getUid();
        $prizetitle = input('prizetitle', '');
        $prizeimgfile = $_FILES?$_FILES['file']:"";
        $opentime = input('opentime', 0);
        $fullnum = input('fullnum', 0);
        $prizemsg = input('prizemsg', '');
        $prizenum = input('prizenum', '');
        $prizetype = input('prizetype', 0);
        if (empty($prizetitle) || empty($prizemsg)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            return parent::respond([], $status, $msg);
        }
        if ($prizeimgfile) {
            //将文件上传到本地
            $picname = UploadFiles::singlefileupload('', $prizeimgfile, Env::get('ROOT_PATH') . 'public/temp/', '');
            $alioss = Config::get('app.alioss');
            $accessKeyId = $alioss['accesskey'];
            $accessKeySecret = $alioss['accesskeysecret'];
            $endpoint = $alioss['endpoint'];
            // 存储空间名称
            $bucket = $alioss['bucket'];
            // 文件名称
            $object = "luckprizeimgs/$picname";
            $filePath = Env::get('ROOT_PATH') . 'public/temp/' . $picname;
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->uploadFile($bucket, $object, $filePath);
            } catch (OssException $e) {
                //文件上传失败
            } finally {
                //删除服务器上的临时文件
                unlink($filePath);
            }
            $prizeimg = $alioss['imgurl'] . $object;
        } else {
            $prizeimg = "";
        }
        if ($opentime) {
            //转换为时间戳
            $opentime = strtotime($opentime);
        }

        $data = array(
            'prize_title' => $prizetitle,
            'prize_img' => $prizeimg,
            'create_time' => time(),
            'open_time' => $fullnum ? 0 : $opentime,
            'full_num' => $fullnum,
            'sponsor_id' => 0,
            'prize_msg' => $prizemsg,
            'prize_num' => $prizenum,
            'prize_type' => $prizetype,
            'sort_num' => 0,
            'user_id' => $userid,
            'is_open' => 0
        );
        $prizeid = self::$luckprizeModel->createprize($data);
        $status = Codes::ACTION_SUC;
        $msg = Codes::get($status);
        return parent::respond(['prizeid' => $prizeid], $status, $msg);
    }

    /**
     * 生成二维码
     */
    public function wechatcode()
    {
        $userid = parent::getUid();//用户id
        $prizeid = input('prizeid', 0);//奖品id
        if (empty($prizeid)) {
            //参数不全
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            return parent::respond([], $status, $msg);
        }
        $resultstr = self::$luckprizeModel->wechatcode($userid, $prizeid);
        return parent::respond($resultstr);
    }

    /**
     * 定时程序调用发送模板消息给中奖者
     */
    public function sendtempmsg()
    {
        $winnerids = input('winnerids');
        $prizeid = input('prizeid');
        $prizename = self::$luckprizeModel->prizedetailmsg($prizeid);
        self::$luckprizeModel->sendwechatmsg($winnerids, $prizename,$prizeid);
        return parent::respond();
    }
}